import store from "@/store";

const baseURL = "https://pcapi-xiaotuxian-front-devtest.itheima.net";

const request = {
  // 请求之前的钩子
  invoke(config) {
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    if (!config.url.startsWith("http")) {
      config.url = baseURL + config.url;
    }
    //超时时间
    config.timeout = 10000
    // 添加请求标识
    config.header = {
      ...config.header,
      "source-client": "miniapp",
    }
    const token = store.state.user.userInfo.token
    if(token){
      config.header.Authorization = token;
    }
  },
  //不管成功失败都关闭加载效果
  complete(res) {
    uni.hideLoading()
  }
}
//请求拦截器
uni.addInterceptor("request", request);
//文件上传
uni.addInterceptor("uploadFile", request);

const http = (config) => {
  return new Promise((resolve, reject) => {
    uni.request({
      ...config,
      success(res) {
        if (res.statusCode >= 200 && res.statusCode <= 300) {
          resolve(res.data)
        } else {
          // reject(res) 
          uni.showToast({
            icon: 'none',
            duration: 1500,
            mask: true,
            title: res.data.message || '系统出错,请重试'
          })
        }
      },
      fail(err) {
        uni.showToast({
          icon: 'none',
          duration: 1500,
          mask: true,
          title: "网络出错"
        })
        reject(err);
      },
    })
  })
}

const methodList = ["GET", "POST", "PUT", "DELETE", "PATCH"];
methodList.forEach((method) => {
  http[method.toLowerCase()] = function (url, data) {
    return http({
      url,
      method,
      data,
    });
  };
});
export default http